from datetime import datetime, date
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, EmailStr, validator


class ClientUserModel(BaseModel):
    """
    客户端用户信息模型
    """
    client_user_id: int = Field(description='客户端用户ID')
    username: str = Field(description='用户名')
    display_name: Optional[str] = Field(description='显示名称')
    email: Optional[str] = Field(description='邮箱地址')
    phone: Optional[str] = Field(description='手机号码')
    avatar: Optional[str] = Field(description='头像URL')
    api_key: str = Field(description='API密钥')
    client_type: int = Field(description='客户端类型：1-个人, 2-企业, 3-开发者')
    plan_type: str = Field(description='计划类型')
    quota_monthly: int = Field(description='月度配额（分钟数）')
    quota_used_monthly: int = Field(description='月度已使用配额')
    quota_reset_date: date = Field(description='配额重置日期')
    rate_limit_per_minute: int = Field(description='每分钟请求限制')
    allowed_models: List[str] = Field(description='允许使用的模型列表')
    allowed_features: Dict[str, bool] = Field(description='允许使用的功能')
    ip_whitelist: Optional[List[str]] = Field(description='IP白名单')
    webhook_url: Optional[str] = Field(description='Webhook回调地址')
    organization: Optional[str] = Field(description='组织机构')
    contact_person: Optional[str] = Field(description='联系人')
    business_type: Optional[str] = Field(description='业务类型')
    status: int = Field(description='状态：0-禁用, 1-启用, 2-冻结')
    is_verified: int = Field(description='是否已验证：0-未验证, 1-已验证')
    last_login_time: Optional[datetime] = Field(description='最后登录时间')
    last_login_ip: Optional[str] = Field(description='最后登录IP')
    create_time: datetime = Field(description='创建时间')
    remark: Optional[str] = Field(description='备注')


class ClientUserCreateModel(BaseModel):
    """
    客户端用户创建模型
    """
    username: str = Field(min_length=3, max_length=50, description='用户名')
    display_name: Optional[str] = Field(max_length=100, description='显示名称')
    email: Optional[EmailStr] = Field(description='邮箱地址')
    phone: Optional[str] = Field(max_length=20, description='手机号码')
    client_type: int = Field(default=1, description='客户端类型：1-个人, 2-企业, 3-开发者')
    plan_type: str = Field(default='free', description='计划类型')
    quota_monthly: int = Field(default=100, description='月度配额（分钟数）')
    allowed_models: List[str] = Field(default=['sensevoice-small'], description='允许使用的模型列表')
    allowed_features: Dict[str, bool] = Field(
        default={'upload': True, 'realtime': False, 'batch': False}, 
        description='允许使用的功能'
    )
    ip_whitelist: Optional[List[str]] = Field(default=None, description='IP白名单')
    webhook_url: Optional[str] = Field(description='Webhook回调地址')
    webhook_secret: Optional[str] = Field(description='Webhook密钥')
    organization: Optional[str] = Field(max_length=100, description='组织机构')
    contact_person: Optional[str] = Field(max_length=50, description='联系人')
    business_type: Optional[str] = Field(max_length=50, description='业务类型')
    remark: Optional[str] = Field(max_length=500, description='备注')

    @validator('plan_type')
    def validate_plan_type(cls, v):
        allowed_plans = ['free', 'basic', 'pro', 'enterprise']
        if v not in allowed_plans:
            raise ValueError(f'计划类型必须是: {", ".join(allowed_plans)}')
        return v

    @validator('client_type')
    def validate_client_type(cls, v):
        if v not in [1, 2, 3]:
            raise ValueError('客户端类型必须是 1(个人)、2(企业) 或 3(开发者)')
        return v


class ClientUserUpdateModel(BaseModel):
    """
    客户端用户更新模型
    """
    display_name: Optional[str] = Field(max_length=100, description='显示名称')
    email: Optional[EmailStr] = Field(description='邮箱地址')
    phone: Optional[str] = Field(max_length=20, description='手机号码')
    avatar: Optional[str] = Field(description='头像URL')
    plan_type: Optional[str] = Field(description='计划类型')
    quota_monthly: Optional[int] = Field(description='月度配额（分钟数）')
    rate_limit_per_minute: Optional[int] = Field(description='每分钟请求限制')
    allowed_models: Optional[List[str]] = Field(description='允许使用的模型列表')
    allowed_features: Optional[Dict[str, bool]] = Field(description='允许使用的功能')
    ip_whitelist: Optional[List[str]] = Field(description='IP白名单')
    webhook_url: Optional[str] = Field(description='Webhook回调地址')
    webhook_secret: Optional[str] = Field(description='Webhook密钥')
    organization: Optional[str] = Field(max_length=100, description='组织机构')
    contact_person: Optional[str] = Field(max_length=50, description='联系人')
    business_type: Optional[str] = Field(max_length=50, description='业务类型')
    status: Optional[int] = Field(description='状态：0-禁用, 1-启用, 2-冻结')
    remark: Optional[str] = Field(max_length=500, description='备注')


class ClientUserQueryModel(BaseModel):
    """
    客户端用户查询模型
    """
    username: Optional[str] = Field(description='用户名（模糊搜索）')
    email: Optional[str] = Field(description='邮箱地址')
    client_type: Optional[int] = Field(description='客户端类型')
    plan_type: Optional[str] = Field(description='计划类型')
    status: Optional[int] = Field(description='状态')
    is_verified: Optional[int] = Field(description='验证状态')
    organization: Optional[str] = Field(description='组织机构（模糊搜索）')
    create_time_start: Optional[datetime] = Field(description='创建时间开始')
    create_time_end: Optional[datetime] = Field(description='创建时间结束')
    page_num: int = Field(default=1, description='页码')
    page_size: int = Field(default=10, description='每页大小')


class ClientUsageModel(BaseModel):
    """
    使用统计模型
    """
    usage_id: int = Field(description='使用统计ID')
    client_user_id: int = Field(description='客户端用户ID')
    usage_date: date = Field(description='统计日期')
    total_requests: int = Field(description='总请求数')
    total_duration: float = Field(description='总音频时长（秒）')
    total_characters: int = Field(description='总识别字符数')
    model_usage: Dict[str, Any] = Field(description='模型使用统计')
    api_calls: int = Field(description='API调用次数')
    success_rate: float = Field(description='成功率（%）')
    avg_response_time: float = Field(description='平均响应时间（秒）')
    error_count: int = Field(description='错误次数')
    peak_concurrent: int = Field(description='峰值并发数')


class ClientUsageQueryModel(BaseModel):
    """
    使用统计查询模型
    """
    client_user_id: Optional[int] = Field(description='客户端用户ID')
    usage_date_start: Optional[date] = Field(description='统计日期开始')
    usage_date_end: Optional[date] = Field(description='统计日期结束')
    page_num: int = Field(default=1, description='页码')
    page_size: int = Field(default=10, description='每页大小')


class ApiKeyModel(BaseModel):
    """
    API密钥模型
    """
    api_key: str = Field(description='API密钥')
    api_secret: str = Field(description='API密钥密码')
    create_time: datetime = Field(description='创建时间')


class ApiKeyResetModel(BaseModel):
    """
    API密钥重置模型
    """
    client_user_id: int = Field(description='客户端用户ID')
    reason: Optional[str] = Field(description='重置原因')


class QuotaModel(BaseModel):
    """
    配额信息模型
    """
    quota_monthly: int = Field(description='月度配额（分钟数）')
    quota_used_monthly: int = Field(description='月度已使用配额')
    quota_remaining: int = Field(description='剩余配额')
    quota_reset_date: date = Field(description='配额重置日期')
    usage_percentage: float = Field(description='使用百分比')


class QuotaUpdateModel(BaseModel):
    """
    配额更新模型
    """
    quota_monthly: Optional[int] = Field(description='月度配额（分钟数）')
    plan_type: Optional[str] = Field(description='计划类型')


class ClientUserStatsModel(BaseModel):
    """
    客户端用户统计模型
    """
    total_users: int = Field(description='总用户数')
    active_users: int = Field(description='活跃用户数')
    verified_users: int = Field(description='已验证用户数')
    by_plan_type: Dict[str, int] = Field(description='按计划类型统计')
    by_client_type: Dict[str, int] = Field(description='按客户端类型统计')
    monthly_usage: Dict[str, float] = Field(description='月度使用情况')


class WebhookConfigModel(BaseModel):
    """
    Webhook配置模型
    """
    webhook_url: Optional[str] = Field(description='Webhook回调地址')
    webhook_secret: Optional[str] = Field(description='Webhook密钥')
    enabled: bool = Field(default=True, description='是否启用')


class ClientUserAuthModel(BaseModel):
    """
    客户端用户认证模型
    """
    api_key: str = Field(description='API密钥')
    client_ip: Optional[str] = Field(description='客户端IP')
    user_agent: Optional[str] = Field(description='用户代理')
    request_id: Optional[str] = Field(description='请求ID')


class ClientUsageCreateModel(BaseModel):
    """
    使用统计创建模型
    """
    client_user_id: int = Field(description='客户端用户ID')
    usage_date: Optional[date] = Field(description='使用日期')
    request_count: Optional[int] = Field(default=1, description='请求次数')
    success_count: Optional[int] = Field(default=0, description='成功次数')
    failed_count: Optional[int] = Field(default=0, description='失败次数')
    audio_duration_minutes: Optional[float] = Field(default=0.0, description='音频时长（分钟）')
    model_used: str = Field(description='使用的模型')
    feature_used: Optional[str] = Field(default='upload', description='使用的功能')
    api_response_time_avg: Optional[float] = Field(default=0.0, description='API平均响应时间（秒）')
    data_transfer_mb: Optional[float] = Field(default=0.0, description='数据传输量（MB）')


class ClientUsageStatsModel(BaseModel):
    """
    使用统计汇总模型
    """
    client_user_id: int = Field(description='客户端用户ID')
    period_start: date = Field(description='统计周期开始')
    period_end: date = Field(description='统计周期结束')
    total_requests: int = Field(description='总请求数')
    successful_requests: int = Field(description='成功请求数')
    failed_requests: int = Field(description='失败请求数')
    total_audio_minutes: float = Field(description='总音频时长（分钟）')
    avg_response_time: float = Field(description='平均响应时间（秒）')
    total_data_transfer_mb: float = Field(description='总数据传输量（MB）')
    most_used_model: str = Field(description='最常用模型')
    most_used_feature: str = Field(description='最常用功能')
    success_rate: float = Field(description='成功率（%）')


class ClientUsageTrendModel(BaseModel):
    """
    使用趋势模型
    """
    date_point: str = Field(description='日期点')
    requests: int = Field(description='请求数')
    audio_minutes: float = Field(description='音频时长（分钟）')
    success_rate: float = Field(description='成功率（%）')
    avg_response_time: float = Field(description='平均响应时间（秒）') 